<template>
  <div>
    <el-card shadow="never">
      <header-title title="水表管理"></header-title>
    </el-card>
    <el-card shadow="never">
      <el-row>
        <el-col :span="21">
          <div>
            水表编号:
            <el-input
              v-model="collectorNo"
              placeholder="请输入内容"
              size="small"
              style="margin-right: 15px;width: 150px;"
            ></el-input>
            <el-button
              @click="search"
              class="button"
              size="small"
              round
              icon="el-icon-search"
              style="margin: 10px 0;"
            >查询</el-button>
          </div>
        </el-col>
        <el-col :span="3">
          <el-button @click="add" class="button" size="small" round>添加水表</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <div>
        <el-table :data="tableData" v-loading="loading" style="width: 100%">
          <el-table-column prop="collectorNo" label="采集器编号"></el-table-column>
          <el-table-column prop="waterMeterNo" label="水表号"></el-table-column>
          <el-table-column prop="waterMeterModel" label="型号"></el-table-column>
          <el-table-column prop="isOnline" label="是否在线"></el-table-column>
          <el-table-column prop="businessName" label="商户名称"></el-table-column>
          <el-table-column prop="stallName" label="摊位名称"></el-table-column>
          <el-table-column prop="sidName" label="设备供应商名称"></el-table-column>
          <el-table-column prop="isOpenAccount" label="是否开户"></el-table-column>
          <el-table-column prop="price" label="单价(每吨)"></el-table-column>
          <el-table-column prop="purchaseCount" label="充值次数"></el-table-column>
          <el-table-column prop="waterValveState" label="水阀状态"></el-table-column>
          <el-table-column prop="isCancelAccount" label="是否销户"></el-table-column>
          <el-table-column label="操作" width="270" fixed="right">
            <template slot-scope="scope">
              <el-button @click="Rechargemeth(scope.row)" type="text" style="color:orange;">充值</el-button>
              <el-button @click="readingMeter(scope.row)" type="text" style="color:#3dc2c2;">抄表</el-button>
              <el-button @click="onMeter(scope.row)" type="text" style="color:#71dc80;">开阀</el-button>
              <el-button @click="offMeter(scope.row)" type="text" style="color:#55b7ff;">关阀</el-button>
              <el-button @click="reset(scope.row)" type="text" style="color:#3dc2c2;">清零</el-button>
              <el-button @click="remove(scope.row)" type="text" style="color:#dc1033;">删除</el-button>
            </template>
          </el-table-column>
          <div slot="empty">
            <img src="../../../assets/blank_tip_page/blank_tip_page.png" alt />
          </div>
        </el-table>
        <el-pagination
          :page-size="perPage"
          :current-page="page"
          :total="total"
          @current-change="changePage"
          style="margin-top: 15px;"
          background
          layout="prev, pager, next"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog title="添加水表" :visible.sync="addDialog" @close="close" v-if="addDialog">
      <div>
        <el-form :model="addModel" label-width="120px" ref="addModel" :rules="rules">
          <el-form-item label="选择采集器：" prop="collectorNo">
            <el-select v-model="addModel.collectorNo" @change="changeCollectorNo" placeholder="请选择">
              <el-option
                v-for="item in collectorNoList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="水表编号：" prop="waterMeterNo">
            <el-input v-model="addModel.waterMeterNo" style="width:194px"></el-input>
          </el-form-item>
          <!--<el-form-item label="水表型号：" prop="waterMeterModel">
            <el-input v-model="addModel.waterMeterModel"></el-input>
          </el-form-item>-->
          <el-form-item label="摊位名称：" prop="marketId">
            <my-select
              ref="mySelectStallName"
              url="api/v1/backend/public/contract/stall"
              :queryParamers="{marketId: this.marketId, type: 2}"
              @selected="mySelectedStall"
            ></my-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save('addModel')">保存水表</el-button>
      </div>
    </el-dialog>
    <el-dialog title="充值" :visible.sync="dialogRecharge" v-if="dialogRecharge" width="25%">
      <el-form :model="Recharge" :rules="rulesRecharge" ref="Recharge">
        <el-form-item label="总金额" :label-width="formLabelWidth" prop="totalprice">
          <el-input
            v-model="Recharge.totalprice"
            autocomplete="off"
            style="width:70%;margin-right:10px"
          ></el-input>元
        </el-form-item>
        <el-form-item label="单价" :label-width="formLabelWidth" prop="price">
          <el-input v-model="Recharge.price" autocomplete="off" style="width:70%;margin-right:10px"></el-input>元
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRecharge = false">取 消</el-button>
        <el-button type="primary" @click="submitRecharge('Recharge')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="清零" :visible.sync="dialogreset" v-if="dialogreset" width="25%">
      <el-form :model="resetdata" :rules="rulesreset" ref="reset">
        <el-form-item label="请输入密码" label-width="100px" prop="password">
          <el-input v-model="resetdata.password" autocomplete="off" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogreset = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitreset('reset')" size="mini">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HeaderTitle from "@/components/HeaderTitle";
import MySelect from "@/components/MySelect";
import store from "@/store";
export default {
  name: "waterMeter",
  components: {
    HeaderTitle,
    MySelect
  },
  data() {
    return {
      marketId: 0,
      loading: true,
      tableData: [],
      collectorNo: "", //	string	false	采集器编号
      perPage: 10, // 每页显示10条
      page: 1, // 当前页
      total: 0,

      addDialog: false,
      addModel: {
        collectorNo: "", //	string	true	采集器编号	11位或12位
        waterMeterNo: "", //	string	true	水表编号	14位，如：13300123456789，前五位13300
        waterMeterModel: "", //l	string	false	水表型号	如：13300,可为空
        stallId: 0, //	int	true	摊位id
        stallName: "" //	string	true	摊位名称
      },
      collectorNoList: [],
      dialogRecharge: false,
      dialogreset: false,
      formLabelWidth: "80px",
      Recharge: {
        totalprice: "",
        price: "",
        id: ""
      },
      resetdata: {
        password: "",
        id: ""
      },
      rules: {
        collectorNo: [
          { required: true, message: "请选择采集器", trigger: "change" }
        ],
        waterMeterNo: [
          { required: true, message: "请输入水表编号", trigger: "change" }
        ],
        marketId: [
          { required: true, message: "请选择摊位名称", trigger: "change" }
        ]
      },
      rulesRecharge: {
        totalprice: [
          { required: true, message: "请选择总金额", trigger: "change" },
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            message: "总金额是整数或两位小数",
            trigger: "change"
          }
        ],
        price: [
          { required: true, message: "请输入单价", trigger: "change" },
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            message: "单价是整数或两位小数",
            trigger: "change"
          }
        ]
      },
      rulesreset: {
        password: [
          { required: true, message: "请选择密码", trigger: "change" },
          {
            pattern: /^[a-zA-Z\d\(\)（）\-\_]+$/,
            message: "密码只可以包含数字，字母，-，_，()",
            trigger: "change"
          }
        ]
      }
    };
  },
  watch: {
    "$store.state.app.marketId"(val, oldVal) {
      this.getDataList(this.collectorNo, this.perPage, this.page);
    }
  },
  mounted() {
    this.getDataList(this.collectorNo, this.perPage, this.page);
    this.marketId = store.state.app.marketId;
  },
  methods: {
    // 获取采集器列表
    getDataList(collectorNo) {
      this.$store
        .dispatch("waterElectricMeter/fetchWaterMeterList", { collectorNo })
        .then(data => {
          this.loading = false;
          for (let i = 0; i < data.items.length; i++) {
            if (data.items[i].isOnline === 1) {
              data.items[i].isOnline = "在线";
            } else {
              data.items[i].isOnline = "离线";
            }
            if (data.items[i].isOpenAccount === 1) {
              data.items[i].isOpenAccount = "已开户";
            } else {
              data.items[i].isOpenAccount = "未开户";
            }
            if (data.items[i].waterValveState === 1) {
              data.items[i].waterValveState = "开启";
            } else {
              data.items[i].waterValveState = "关闭";
            }
            if (data.items[i].isCancelAccount === 1) {
              data.items[i].isCancelAccount = "已销户";
            } else {
              data.items[i].isCancelAccount = "正常";
            }
          }
          this.tableData = data.items;
          this.total = data.total;
        })
        .catch(err => {
          this.loading = false;
          this.tableData = [];
          this.total = 0;
        });
    },
    search() {
      this.page = 1;
      this.getDataList(this.collectorNo, this.perPage, this.page);
    },
    changePage(num) {
      this.page = num;
      this.getDataList(this.collectorNo, this.perPage, num);
    },
    // 点击添加
    add() {
      this.addDialog = true;
      // 获取采集器列表
      this.$store
        .dispatch("waterElectricMeter/fetchCollectorNoList")
        .then(data => {
          let items = [];
          for (let item of data) {
            items.push({
              value: item.id + "",
              label: item.collectorNo
            });
          }
          this.collectorNoList = items;
        })
        .catch(err => {
          this.collectorNoList = [];
        });
    },
    changeCollectorNo(type) {
      // 用原数据查id对应name
      let obj = {};
      obj = this.collectorNoList.find(item => {
        // 这里的 this.supplierList 就是上面遍历的数据源
        return item.value === type; // 筛选出匹配数据 数据源里的 id 等于 当前选中的 id
      });
      this.addModel.collectorNo = obj.label;
    },
    // 摊位 自动完成
    mySelectedStall(obj) {
      this.addModel.stallId = obj.exData.id;
      this.addModel.stallName = obj.exData.name;
    },
    save(addModel) {
      console.log(this.addModel);
      this.$refs[addModel].validate(valid => {
        if (valid) {
          this.addDialog = false;
          this.$store
            .dispatch("waterElectricMeter/fetchSaveWaterMeter", this.addModel)
            .then(data => {
              console.log("success?");
              console.log(data);
              // 成功之后调用列表
              if (data) {
                this.$message({
                  type: "success",
                  message: "新增成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
              // 调用 close
              this.addModel = {};
              this.$refs["mySelectStallName"].clear();
            })
            .catch(err => {});
        } else {
          this.$message.error("有必填项未填");
          return false;
        }
      });
    },
    close() {
      this.addModel = {};
    },
    // 点击删除
    remove(row) {
      let id = row.id;
      //        this.$confirm(`是否确定要删除采集器 "${row.sid}"`, '提示', {
      this.$confirm(`是否确定要删除?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("waterElectricMeter/fetchRemoveWaterMeter", { id })
            .then(data => {
              console.log(data);
              if (data.data === []) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
            });
        })
        .catch(err => {});
    },
    //充值
    Rechargemeth(row) {
      this.Recharge.id = row.id;
      this.dialogRecharge = true;
    },
    submitRecharge(formrules) {
      this.$refs[formrules].validate(valid => {
        if (valid) {
          this.$store
            .dispatch("waterRecharge/getRecharge", {
              id: this.Recharge.id,
              money: this.Recharge.totalprice,
              price: this.Recharge.price * 100
            })
            .then(data => {
              if (data) {
                this.$message({
                  type: "success",
                  message: "充值成功!"
                });
                this.getDataList(this.searchName, this.perPage, this.page);
                this.dialogRecharge = false;
              } else if (data == undefined) {
                this.dialogRecharge = true;
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          this.dialogRecharge = true;
          this.$message.error("有必填项未填");
          return false;
        }
      });
    },
    // 清零
    reset(row) {
      this.dialogreset = true;
      this.resetdata.id = row.id;
    },
    submitreset(formrules) {
      this.$refs[formrules].validate(valid => {
        if (valid) {
          this.$store
            .dispatch("yzpassword/getPassword", {
              password: this.resetdata.password
            })
            .then(data => {
              if (data.state == true) {
                this.dialogreset = false;

                this.$confirm(`要清零?`, "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                })
                  .then(() => {
                    this.$store
                      .dispatch("waterElectricMeter/fetchResetWater", {
                        id: this.resetdata.id
                      })
                      .then(data => {
                        console.log(data.data);
                        if (data.data) {
                          this.$message({
                            type: "success",
                            message: "清零成功!"
                          });
                        }
                        this.getDataList(
                          this.searchName,
                          this.perPage,
                          this.page
                        );
                      });
                  })
                  .catch(err => {});
              } else {
                this.$message.error("密码错误");
              }
            });
        } else {
          this.dialogRecharge = true;
          this.$message.error("有必填项未填");
          return false;
        }
      });
    },
    // 抄表
    readingMeter(row) {
      let id = row.id;
      this.$confirm(`点击了抄表数据?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("waterElectricMeter/fetchReadWaterMeter", { id })
            .then(data => {
              console.log(data.data);
              if (data.data) {
                this.$message({
                  type: "success",
                  message: "抄表成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
            });
        })
        .catch(err => {});
    },
    // 开阀
    onMeter(row) {
      //        controlStatus	int	true	闸门状态 1.合闸 2.拉闸
      console.log(row);
      let id = row.id;
      const controlStatus = 1;
      this.$confirm(`设置开阀?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$store
          .dispatch("waterElectricMeter/fetchPullWaterMeter", {
            id,
            controlStatus
          })
          .then(data => {
            console.log(data.data);
            if (data.data) {
              this.$message({
                type: "success",
                message: "设置成功!"
              });
            }
            this.getDataList(this.searchName, this.perPage, this.page);
          })
          .catch(err => {});
      });
    },
    // 关阀
    offMeter(row) {
      //        controlStatus	int	true	闸门状态 1.合闸 2.拉闸
      console.log(row);
      let id = row.id;
      const controlStatus = 2;
      this.$confirm(`设置关阀?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("waterElectricMeter/fetchPullWaterMeter", {
              id,
              controlStatus
            })
            .then(data => {
              console.log(data.data);
              if (data.data) {
                this.$message({
                  type: "success",
                  message: "设置成功!"
                });
              }
              this.getDataList(this.searchName, this.perPage, this.page);
            });
        })
        .catch(err => {});
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table .cell {
  text-align: center;
}
.button {
  background: #64d9d6;
  color: #fff;
  margin-left: 40px;
}
</style>
